package utils

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"math/big"
	"net/mail"
	"os"
	"strconv"
	"strings"

	"regexp"

	"github.com/google/uuid"
)

var (
	UIDMatcher = regexp.MustCompile("^[a-zA-Z0-9_]([a-zA-Z0-9-_]{1,30}[a-zA-Z0-9_])$")
)

// ConvertStringToInt32 converts a string to int32.
func ConvertStringToInt32(src string) (int32, error) {
	parsed, err := strconv.ParseInt(src, 10, 32)
	if err != nil {
		return 0, err
	}
	return int32(parsed), nil
}

// HasPrefixes returns true if the string s has any of the given prefixes.
func HasPrefixes(src string, prefixes ...string) bool {
	for _, prefix := range prefixes {
		if strings.HasPrefix(src, prefix) {
			return true
		}
	}
	return false
}

// ValidateEmail validates the email.
func ValidateEmail(email string) bool {
	if _, err := mail.ParseAddress(email); err != nil {
		return false
	}
	return true
}

func GenUUID() string {
	return uuid.New().String()
}

var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

// RandomString returns a random string with length n.
func RandomString(n int) (string, error) {
	var sb strings.Builder
	sb.Grow(n)
	for i := 0; i < n; i++ {
		// The reason for using crypto/rand instead of math/rand is that
		// the former relies on hardware to generate random numbers and
		// thus has a stronger source of random numbers.
		randNum, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
		if err != nil {
			return "", err
		}
		if _, err := sb.WriteRune(letters[randNum.Uint64()]); err != nil {
			return "", err
		}
	}
	return sb.String(), nil
}

// ReplaceString replaces all occurrences of old in slice with new.
func ReplaceString(slice []string, old, new string) []string {
	for i, s := range slice {
		if s == old {
			slice[i] = new
		}
	}
	return slice
}

func HashString(input string) string {
	hasher := sha256.New()

	// 将输入字符串转换为字节切片并写入哈希器
	hasher.Write([]byte(input))

	// 计算哈希值并转换为十六进制字符串
	sum := hasher.Sum(nil)
	return hex.EncodeToString(sum)
}

func ComputeFileHash(filePath string) (string, error) {
	hasher := sha256.New()
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// 将文件内容写入哈希对象
	if _, err := io.Copy(hasher, file); err != nil {
		return "", err
	}

	// 返回哈希结果
	sum := hasher.Sum(nil)
	return hex.EncodeToString(sum), nil
}

func Contains(slice []int32, element int32) bool {
	for _, item := range slice {
		if item == element {
			return true
		}
	}
	return false
}

func RemoveElement(slice []int32, element int32) []int32 {
	var result []int32
	for _, item := range slice {
		if item != element {
			result = append(result, item)
		}
	}
	return result
}

func BoolPtr(b bool) *bool {
	return &b
}
